package com.mobilepay.moneypig.model.activity.launcher;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.githang.statusbar.StatusBarCompat;
import com.mobilepay.moneypig.R;
import com.mobilepay.moneypig.base.BaseActivity;
import com.mobilepay.moneypig.base.NoDoubleClickListener;
import com.mobilepay.moneypig.config.Constant;
import com.mobilepay.moneypig.config.Key;
import com.mobilepay.moneypig.config.NetConfig;
import com.mobilepay.moneypig.okhttp.HttpUtils;
import com.mobilepay.moneypig.response.ResponseResult;
import com.mobilepay.moneypig.timecount.CodeTimerService;
import com.mobilepay.moneypig.timecount.CountDownTimerUtil;
import com.mobilepay.moneypig.utils.CommonUtil;
import com.mobilepay.moneypig.utils.GsonUtil;
import com.mobilepay.moneypig.view.WebViewActivity;

/**
 * Created by xlm on 2017/7/13 0013
 */

public class RegisterActivity extends BaseActivity {
    private static final String TAG = "RegisterActivity";

    private TextView mTextViewCode;
    private Button mButtonNext;
    private ImageView mImageBack;
    private EditText mMobile, mHuoQu, mPassWord, mInvite;
    private EditText mPasswordTwo;
    private RelativeLayout mRelativeSao;
    private TextView mTextDocument;

    @Override
    protected void onSetContentView() {
        setContentView(R.layout.activity_regist);
    }

    @Override
    protected void afterSetContentView() {
        super.afterSetContentView();
        StatusBarCompat.setStatusBarColor(this, Color.parseColor("#40000000"));
    }

    @Override
    protected void initViews() {
        mTextViewCode = (TextView) findViewById(R.id.regist_code);
        mImageBack = (ImageView) findViewById(R.id.regist_back);
        mMobile = (EditText) findViewById(R.id.regist_mobile);
        mHuoQu = (EditText) findViewById(R.id.regist_huoqu);
        mPassWord = (EditText) findViewById(R.id.regist_pw);
        mPasswordTwo = (EditText) findViewById(R.id.regist_pw_two);
        mInvite = (EditText) findViewById(R.id.regist_invite);
        mButtonNext = (Button) findViewById(R.id.regis_next);
        mRelativeSao = (RelativeLayout) findViewById(R.id.regist_sao);
        mTextDocument = (TextView) findViewById(R.id.user_document);
    }

    @Override
    protected void afterOnCreate(Bundle savedInstanceState) {

    }

    @Override
    protected void onSetListener() {
        mButtonNext.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View view) {
                super.onNoDoubleClick(view);
                onRegist();
            }
        });
        mImageBack.setOnClickListener(this);
        mTextViewCode.setOnClickListener(this);
        mRelativeSao.setOnClickListener(this);
        mTextDocument.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.regist_code:
                getYzCode();
                break;
            case R.id.regist_sao:
//                Intent intent1 = new Intent();
//                intent1.setClass(getThis(), MipcaActivityCapture.class);
//                startActivityForResult(intent1, REQUST_QRCODE);
                break;
            case R.id.regist_back:
                finish();
                break;
            case R.id.user_document:
                Intent intent2 = new Intent();
                intent2.setClass(getThis(), WebViewActivity.class);
                intent2.putExtra(Key.TITLE, "用户协议");
                intent2.putExtra(Key.URL, NetConfig.USER_DOCUMENT);
                startActivity(intent2);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            String mCode = data.getStringExtra("result");
            mInvite.setText(mCode);
            mInvite.setSelection(mCode.length());
        }
    }


    // 注册广播
    private static IntentFilter updateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(CodeTimerService.IN_RUNNING);
        intentFilter.addAction(CodeTimerService.END_RUNNING);
        return intentFilter;
    }

    String sMobile;
    // 广播接收者
    private final BroadcastReceiver mUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            switch (action) {
                case CodeTimerService.IN_RUNNING:
                    if (mTextViewCode.isEnabled())
                        mTextViewCode.setEnabled(false);
                    // 正在倒计时
                    mTextViewCode.setText(intent.getStringExtra("time"));
                    sMobile = intent.getStringExtra("mobile");
                    mMobile.setText(sMobile);
                    mMobile.setSelection(sMobile.length());
                    break;
                case CodeTimerService.END_RUNNING:
                    // 完成倒计时
                    mTextViewCode.setEnabled(true);
                    mTextViewCode.setText("获取验证码");
                    break;
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        // 注册广播
        registerReceiver(mUpdateReceiver, updateIntentFilter());
    }

    @Override
    protected void onPause() {
        super.onPause();
        // 移除注册
        unregisterReceiver(mUpdateReceiver);
    }

    /**
     * get yzcode
     */
    private void getYzCode() {
        String mobile = mMobile.getText().toString();
        if (CommonUtil.isEmpty(mobile)) {
            showToastShort("请输入手机号码");
            return;
        }
        if (!CommonUtil.isMobile(mobile)) {
            showToastShort("请输入正确的手机号码");
            return;
        }
        HttpUtils.RequestParam param = new HttpUtils.RequestParam();
        param.add("method", NetConfig.sendsms);
        param.add("mobile", mMobile.getText().toString());
        param.add("sign", param.getMd5String());
        showProgress("验证码发送中");
        HttpUtils.getInstance().params(param).executePost(new HttpUtils.HttpListener() {
            @Override
            public void onException(Throwable e) {
                super.onException(e);
                dismissProgress();
                if (CommonUtil.isForeground(getThis())) {
                    showToastShort(getString(R.string.net_state));
                }
            }

            @Override
            public void onHttpSuccess(String string) {
                super.onHttpSuccess(string);
                dismissProgress();
                if (HttpUtils.isJson(string)) {
                    ResponseResult result = GsonUtil.GsonToBean(string, ResponseResult.class);
                    showToastShort(result.getInfo());
                    if (result.getStatus() == Constant.STATUS_CODE_SUCCESS) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
//                                Intent intent = new Intent();
//                                intent.setClass(RegisterActivity.this, CodeTimerService.class);
//                                intent.putExtra("mobile", mMobile.getText().toString());
//                                startService(intent);
                                new CountDownTimerUtil(mTextViewCode, NetConfig.cutdown_time, 1000).start();
                            }
                        });
                    }
                }
            }
        });
    }


    /**
     * regist
     */
    private void onRegist() {
        final String mobile = mMobile.getText().toString();
        final String password = mPassWord.getText().toString();
        String password_two = mPasswordTwo.getText().toString();
        String code = mHuoQu.getText().toString();
        String invite = mInvite.getText().toString();
        if (CommonUtil.isEmpty(mobile)) {
            showToastShort("请输入手机号码");
            return;
        }
        if (!CommonUtil.isMobile(mobile)) {
            showToastShort("请输入正确的手机号码");
            return;
        }
        if (CommonUtil.isEmpty(code)) {
            showToastShort("请输入验证码");
            return;
        }
        if (CommonUtil.isEmpty(password)) {
            showToastShort("请输入密码");
            return;
        }
        if (CommonUtil.isEmpty(password_two)) {
            showToastShort("请再次输入密码");
            return;
        }
        if (CommonUtil.isEmpty(invite)) {
            showToastShort("请输入邀请码");
            return;
        }
        if (!password.equals(password_two)) {
            showToastShort("密码输入不一致,请重新输入");
            mPasswordTwo.setText(null);
            return;
        }
        HttpUtils.RequestParam param = new HttpUtils.RequestParam();
        param.add("method", NetConfig.register);
        param.add("username", mobile);
        param.add("verify", code);
        param.add("password", password);
        param.add("invitation_code", invite);
        param.add("user_type", "2");
        param.add("sign", param.getMd5String());
        showProgress("注册中");
        HttpUtils.getInstance().params(param).executePost(new HttpUtils.HttpListener() {
            @Override
            public void onException(Throwable e) {
                super.onException(e);
                dismissProgress();
                if (CommonUtil.isForeground(getThis())) {
                    showToastShort(getString(R.string.net_state));
                }
            }

            @Override
            public void onHttpSuccess(String string) {
                super.onHttpSuccess(string);
                if (HttpUtils.isJson(string)) {
                    ResponseResult result = GsonUtil.GsonToBean(string, ResponseResult.class);
                    showToastShort(result.getInfo());
                    if (result.getStatus() == 1) {
                        Intent intent = new Intent();
                        intent.putExtra(Key.USERNAME, mobile);
                        intent.putExtra(Key.PASSWORD, password);
                        setResult(RESULT_OK, intent);
                        finishActivity(true);
                    } else {
                        dismissProgress();
                    }
                }
            }
        });
    }

//    /**
//     * 登录
//     */
//    private void onLogin(final String mobile, final String password) {
//        HttpUtils.RequestParam param = new HttpUtils.RequestParam();
//        param.add("method", NetConfig.login);
//        param.add("username", mobile);
//        param.add("password", password);
//        param.add("user_type", "2");
//        param.add("sign", param.getMd5String());
//        showProgress("登陆中");
//        HttpUtils.getInstance().params(param).executePost(new HttpUtils.HttpListener() {
//            @Override
//            public void onException(Throwable e) {
//                super.onException(e);
//                dismissProgress();
//                if (CommonUtil.isForeground(getThis())) {
//                    showToastShort(getString(R.string.net_state));
//                }
//            }
//
//            @Override
//            public void onHttpSuccess(String string) {
//                super.onHttpSuccess(string);
//                dismissProgress();
//                if (HttpUtils.isJson(string)) {
//                    ResponseResult responseResult = GsonUtil.GsonToBean(string, ResponseResult.class);
//                    if (responseResult.getStatus() == 1) {
//                        UserInfo userInfo = GsonUtil.GsonToBean(string, UserInfo.class);
//                        App.getApp().setUserInfo(userInfo);//保存用户信息
//                        PreferenceUtil.setParam(getThis(), Key.USERNAME, mobile);
//                        PreferenceUtil.setParam(getThis(), Key.PASSWORD, password);
//                        startActivity(MainActivity.class);
//                        finish();
//                    } else {
//                        showToastShort(responseResult.getInfo());
//                    }
//                }
//            }
//        });
//    }
}
